﻿var SelectareDepartamentPage = function(pageContainer) {

    SelectareDepartamentPage.superclass.constructor.call(this, pageContainer);

    var self = this;
    var currentCallback = null;
    var currentIndex = 0;
    var pageSize = 10;
    var initialPageSize = 20;
    var isLoading = false;
    var searchResultsInfo = null;
    var searchBar = null;
    var visibleElements = 0;
    var departamente = new Array();
    var pct_id = 0;

    this.CanGoBack = false;
    this.isPopup = true;

    var Elements = {
        list: pageContainer.find(".list"),
        searchInput: pageContainer.find(".searchInput"),
        loader: pageContainer.find(".loadMore")
    };

    var Templates = {
        departamentTemplate: pageContainer.find('.departamentTemplate'),
        departamentTemplateCompiled: null
    };

    var resetList = function() {
        currentIndex = 0;
        isLoading = false;
        Elements.list.empty();
        departamente = new Array();
    };

    this.refresh = function(pct, callback) {
        if (pct.Id != pct_id) {
            resetList();
            pct_id = pct.Id;
        }
        currentCallback = callback;
        self.getPullUpData();
    };

    this.getPullUpData = function() {
        if (isLoading)
            return;

        isLoading = true;

        Elements.loader.show();
        var noItemsToLoad = currentIndex ? pageSize : initialPageSize;
        var searchText = searchBar.getSearchText();
        app.TMMService.General.GetDepartamente(pct_id, searchText, currentIndex, noItemsToLoad, function(response) {
            isLoading = false;
            if (response.Exception)
                Elements.loader.hide();
            else {
                if (currentIndex != response.Ref)
                    return;

                addToList(response.FinalResult);

                if (!visibleElements)
                    calculateVisibleElements();

                if (!response.FinalResult.length || (response.FinalResult.length < visibleElements))
                    Elements.loader.hide();
                else if (!currentIndex)
                    Elements.loader.show();

                currentIndex += response.FinalResult.length;
            }
        });
    };

    var calculateVisibleElements = function() {
        visibleElements = Math.ceil($(window).height() / Elements.list.find(".search-settings-select-box:first").outerHeight());
    };

    var addToList = function(data) {
        if (!data)
            data = new Array();

        if (!Templates.departamentTemplateCompiled) {
            var source = Templates.departamentTemplate.html();
            Templates.departamentTemplateCompiled = Handlebars.compile(source);
        }

        var html = "";
        for (var i = 0; i < data.length; i++) {
            var dpt = data[i];
            departamente.push(dpt);
            html += Templates.departamentTemplateCompiled(dpt);
        }

        Elements.list.append(html);

        Elements.list.find('.list-element').unbind().click(function(e) {
            if (!currentCallback)
                return;
            var index = Elements.list.children().index($(this).parent());
            currentCallback(departamente[index]);

            return Event.stopEvent(e);
        });
    };

    self.initialize = override(self.initialize, function() {
        self.Title = translate('Module_Title_SelectareDepartament');
        addSearchBar();
        addResultsInfo(Elements.list);
        app.translatePage(app.Pages.SelectareDepartament);

        pageContainer.bind('onBeforePageShow', function() {
            app.Phone.setBackbtnVisible(true);
        });

    });

    var addResultsInfo = function(element) {
        element.before($("#searchResultsInfoTemplate").html());
        var searchResultsInfoContainer = pageContainer.find(".search-results-container");
        searchResultsInfo = new SearchResultsInfo(searchResultsInfoContainer);
        searchResultsInfo.hide();
    };

    var addSearchBar = function() {
        pageContainer.find('.content div:first').before($("#searchBarTemplate").html());
        var searchBarContainer = pageContainer.find(".search-bar:first");
        searchBar = new SearchBar(searchBarContainer);
        searchBar.initialize();
        searchBarContainer.show();
        searchBarContainer
            .bind('getData', function(e) {
                if (!searchBar.getSearchText())
                    return searchBar.hideSearch();
                if (e.Data.reset)
                    resetList();
                self.getPullUpData();
            })
            .bind('cancel', function(e) {
                resetList();
                self.getPullUpData();
            }).bind('settings', function(e) {
                filter.toggle();
            });

    };

    this.setModuleAction = override(self.setModuleAction, function() {
        if (app.Phone)
            app.Phone.setModuleAction(ModuleActions.None);
    });
};
extend(SelectareDepartamentPage, TMMobilePage);